# src/middleware/auth.py
from fastapi import Request, HTTPException
from fastapi.responses import JSONResponse
from src.config import settings  # 假设您有配置文件
path_whitelist = settings.get_path_whitelist()
async def auth_middleware(request: Request, call_next):
    print(request.url.path)
    # 路径白名单检查
    if request.url.path in path_whitelist:
        return await call_next(request)  # 跳过验证，直接处理请求
    # 1. 检查IP白名单
    client_ip = request.client.host
    if client_ip not in settings.IP_WHITELIST:
        return JSONResponse(
            content={"code": 403, "data": {}, "msg": f"IP {client_ip}不在白名单中"},
            status_code=403
        )

    # 2. 检查Token（从Header获取）
    token = request.headers.get("Authorization")
    if not token:
        return JSONResponse(
            content={"code": 401, "data": {}, "msg": "缺少Authorization头"},
            status_code=401
        )

    # 验证Token格式（示例：Bearer token）
    if not token.startswith("Bearer "):
        return JSONResponse(
            content={"code": 401, "data": {}, "msg": "无效的Token格式"},
            status_code=401
        )

    # 提取并验证Token
    token = token.split(" ")[1]
    if token != settings.API_TOKEN:  # 从配置获取真实Token
        return JSONResponse(
            content={"code": 401, "data": {}, "msg": "无效的Token"},
            status_code=401
        )

    # 验证通过，继续处理请求
    response = await call_next(request)
    return response
# 示例使用
# app.py
# from fastapi import FastAPI
# from src.middleware.auth import auth_middleware
#
# app = FastAPI()
# app.middleware("http")(auth_middleware)  # 全局注册中间件